package org.insia.smartposse.action;

import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.criterion.Order;
import org.insia.smartposse.beans.Application;
import org.insia.smartposse.form.ApplicationForm;
import org.insia.smartposse.form.BooksForm;
import org.insia.smartposse.manager.ApplicationManager;
import org.insia.smartposse.manager.FreelanceBookManager;
import org.insia.smartposse.manager.JobProjectManager;
import org.insia.smartposse.manager.ProjectManager;
import org.insia.smartposse.manager.ProjectsListManager;
import org.insia.smartposse.manager.UserManager;
import org.insia.smartposse.manager.list.FreelanceBooksListManager;
import org.insia.smartposse.mapping.dao.ApplicationDAO;
import org.insia.smartposse.mapping.dao.UsersDAO;
import org.insia.smartposse.mapping.Users;

/**
 * @author bvuagnia
 */

public class ApplicationAction extends DispatchAction {

	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		req.setAttribute("applicationList", new ApplicationDAO().findAll());
		req.setAttribute("list", true);
		return mapping.findForward("list");
	}
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		//Init
		UserManager user = (UserManager)req.getSession().getAttribute("User");
		ApplicationForm applicationForm = (ApplicationForm)form;
		Integer freelanceId = (Integer)req.getSession().getAttribute("ApplicationCreatefreeLanceID");
		Integer jobProjectId = (Integer)req.getSession().getAttribute("ApplicationCreateJobProjectId");

		//DAO
		JobProjectManager jobProject = new JobProjectManager(jobProjectId);
		ApplicationManager managerDAO = new ApplicationManager();
		managerDAO.setAccept(ApplicationManager.NODECIDED);
		managerDAO.setJobProject(jobProject);
		managerDAO.setFrom(user.getUser());
		managerDAO.setFreelance(new UserManager(freelanceId));
		managerDAO.setMessage(applicationForm.getMessage());
		managerDAO.setSalary(applicationForm.getSalary());
		managerDAO.save();

		String emailto;
		if(user.getId() == freelanceId)
		{//le freelance fait une deamande pour un JobProject
			emailto = jobProject.getProject().getManager().getEmail();

		}else{//Un manager fait une demande � un freeLance
			emailto = jobProject.getFreelance().getEmail();

		}


		/**/

		String emailfrom = "cmougel@insia.org";

		// R�cup�re les propri�t�s du syst�me
		Properties props = System.getProperties();

		// Sp�cification du serveur mail
		props.put("mail.smtp.host", "smtp.insia.org");

		// R�cup�re la session
		Session session = Session.getDefaultInstance(props, null);

		// D�finition du message
		MimeMessage message = new MimeMessage(session);
		//Sp�cification de l'exp�diteur
		message.setFrom(new InternetAddress(emailfrom));
		//Sp�cification du destinataire
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailto));
		//Sujet du message
		final ResourceBundle bundle = ResourceBundle.getBundle("org.insia.smartposse.bundle");
		message.setSubject(bundle.getString("mail.title"));
		//Texte du message
		message.setText(bundle.getString("mail.content") + " http://localhost:8000/smartposse/application.do?cmd=reponseEmail&ApplicationID=" + managerDAO.getId());
		// Envoie le message
		Transport.send(message);


		req.setAttribute("applicationList", new ApplicationDAO().findAll());
		req.getSession().removeAttribute("ApplicationCreatefreeLanceID");
		req.getSession().removeAttribute("ApplicationCreateJobProjectId");
		req.setAttribute("list", true);

		// Message ok Application
		req.getSession().setAttribute("message", true);
		//resp.sendError(arg0, arg1)
		req.getSession().setAttribute("messageMsg", "jobs.list.applicationOK");// A faire
		resp.sendRedirect(req.getContextPath() + "/jobs.do");
		return null;
	}
	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		if(null != req.getParameter("freeLanceID"))
			req.getSession().setAttribute("ApplicationCreatefreeLanceID", new Integer(req.getParameter("freeLanceID")));
		else{
			Integer userId = ((UserManager)req.getSession().getAttribute("User")).getId();
			req.getSession().setAttribute("ApplicationCreatefreeLanceID",userId);
		}
		if(null != req.getParameter("JobProjectId")){
			req.getSession().setAttribute("ApplicationCreateJobProjectId",new Integer(req.getParameter("JobProjectId")));
			req.setAttribute("create", true);
		}else{
			req.setAttribute("error", true);
			//resp.sendError(arg0, arg1)
			req.setAttribute("errorMsg", "Missing Arg JobProjectId=???");// A faire
		}
		req.setAttribute("list", true);
		return mapping.findForward("create");
	}
	public ActionForward reponseEmail(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		if(null == req.getParameter("ApplicationID"))
		{
			req.setAttribute("error", true);
			//resp.sendError(arg0, arg1)
			req.setAttribute("errorMsg", "Missing Arg ApplicationID=???");
		}else{
			Integer applicationId = Integer.parseInt(req.getParameter("ApplicationID"));
			ApplicationManager manager = new ApplicationManager(applicationId);
			req.getSession().setAttribute("ReponseMailApplicationManager", manager);
			//Verification

			UserManager currentUser = ((UserManager)req.getSession().getAttribute("User"));
			Integer userID = currentUser.getId();
			Integer dd = manager.getFreelance().getId();
			Integer gg = manager.getFrom().getId();

			if(manager.getFreelance().getId().equals(currentUser.getId()) )//^ manager.getFrom().getId() == currentUser.getId()
			{
				//Project
				ProjectManager proMan = new ProjectManager(manager.getJobProject().getProject().getId());
				if (null == proMan.getProject()){
					resp.setStatus(404);
					return null;
				}
				req.setAttribute("project", proMan);

				//JobProject
				req.setAttribute("jobProject", manager.getJobProject());


				req.setAttribute("reponseEmail", true);
			}else{
				req.setAttribute("error", true);
				req.setAttribute("errorMsg", "Restriction Zone");
			}
		}
		return mapping.findForward("create");
	}
	public ActionForward reponseEmailSave(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		ApplicationManager manager = (ApplicationManager)req.getSession().getAttribute("ReponseMailApplicationManager");

		Object toto = req.getAttribute("submit");//A voir
		req.setAttribute("applicationList", new ApplicationDAO().findAll());
		req.setAttribute("list", true);
		return mapping.findForward("list");
	}
	public ActionForward evaluationCreate(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		if(null == req.getParameter("ApplicationID"))
		{
			req.setAttribute("error", true);
			req.setAttribute("errorMsg", "Missing Arg ApplicationID=???");
		}else{
			ApplicationManager manager = new ApplicationManager(Integer.parseInt(req.getParameter("ApplicationID")));
			req.getSession().setAttribute("EvalApplication", manager);
			//req.setAttribute("evalManager", true);
			req.setAttribute("evalFreelance", true);
		}


		req.setAttribute("evaluationCreate", true);
		return mapping.findForward("evaluationCreate");
	}
	public ActionForward evaluationAdd(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		if(null == req.getSession().getAttribute("EvalApplication"))
		{
			req.setAttribute("error", true);
			req.setAttribute("errorMsg", "Missing Session Attribut EvalApplication");
		}else{
			ApplicationManager manager =(ApplicationManager) req.getSession().getAttribute("EvalApplication");
			ApplicationForm result = (ApplicationForm)  form;
			manager.setCommentManager(result.getCommentManager());
			manager.setGradeManager(result.getGradeManager());
			manager.save();
		}


		req.setAttribute("list", true);
		return mapping.findForward("list");
	}
}
